package com.yuxl.admin.common.graphql.config;

import graphql.GraphQLContext;
import graphql.execution.CoercedVariables;
import graphql.language.StringValue;
import graphql.language.Value;
import graphql.schema.*;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

/**
 * 自定义GraphQL DateTime标量类型
 * 用于处理日期时间的序列化和反序列化
 */
@Component
public class GraphQLDateTime {

    // 定义日期时间格式
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * 创建自定义的DateTime标量类型
     * @return GraphQLScalarType实例
     */
    public GraphQLScalarType dateTimeType() {
        return GraphQLScalarType.newScalar()
                .name("DateTime")
                .description("DateTime scalar")
                .coercing(new Coercing<LocalDateTime, String>() {
                    /**
                     * 序列化方法：将LocalDateTime对象转换为字符串
                     */
                    @Override
                    public String serialize(Object dataFetcherResult, GraphQLContext context, Locale locale) throws CoercingSerializeException {
                        if (dataFetcherResult instanceof LocalDateTime) {
                            // 将LocalDateTime格式化为字符串
                            return ((LocalDateTime) dataFetcherResult).format(formatter);
                        }
                        throw new CoercingSerializeException("Expected a LocalDateTime object.");
                    }

                    /**
                     * 反序列化方法：将输入的字符串解析为LocalDateTime对象
                     */
                    @Override
                    public LocalDateTime parseValue(Object input, GraphQLContext context, Locale locale) throws CoercingParseValueException {
                        if (input instanceof String) {
                            // 将字符串解析为LocalDateTime
                            return LocalDateTime.parse((String) input, formatter);
                        }
                        throw new CoercingParseValueException("Expected a String in format yyyy-MM-dd HH:mm:ss");
                    }

                    /**
                     * 解析GraphQL查询中的日期时间字面值
                     */
                    @Override
                    public LocalDateTime parseLiteral(Value<?> input, CoercedVariables variables, GraphQLContext context, Locale locale) throws CoercingParseLiteralException {
                        if (input instanceof StringValue) {
                            // 将StringValue解析为LocalDateTime
                            return LocalDateTime.parse(((StringValue) input).getValue(), formatter);
                        }
                        throw new CoercingParseLiteralException("Expected a StringValue in format yyyy-MM-dd HH:mm:ss");
                    }
                })
                .build();
    }
}
